package com.yumaolin.deepunderstand.leetcode.algorithm.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 94. 非递归的方式实现中序遍历
 */
public class MediumOrderTraversal {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> orderList = new ArrayList<>();
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (!stack.empty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            orderList.add(top.val);
            cur = top.right;
        }
        return orderList;
    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
